package com.pirestupppai.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.pirestupppai.R;
import com.pirestupppai.adapter.HomeTagAdapter;
import com.pirestupppai.base.BaseFragment;
import com.pirestupppai.bean.HomeBanner;
import com.pirestupppai.bean.HomeTagTwoItem;
import com.pirestupppai.bean.TagItem;
import com.pirestupppai.common.Constant;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.ui.activity.SearchActivity;
import com.pirestupppai.widgets.view.BannerView;
import com.pirestupppai.widgets.view.LoadMoreFooter;
import com.pirestupppai.widgets.view.ModuleView;
import com.pirestupppai.widgets.view.SingleModuleView;
import com.pirestupppai.widgets.view.VpSwipeRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.pirestupppai.R.id.home_swipe_layout;

/**
 * 首页
 *
 * @author: xiaoluo
 * @date: 2017-03-03 17:30
 */
public class HomeFragment extends BaseFragment {
    private final static String TAG = HomeFragment.class.getSimpleName();

    @BindView(R.id.appbar)
    AppBarLayout appBarLayout;
    @BindView(R.id.home_recycler_view)
    RecyclerView recyclerView;
    @BindView(home_swipe_layout)
    VpSwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.search_bar)
    RelativeLayout searchBar;
    @BindView(R.id.status_bar)
    View statusBar;

    private HomeTagAdapter mHomeListAdapter;
    private LinearLayoutManager mLinearLayoutManager;
    private LoadMoreFooter mFooterView;

    private int mPosition = 0;  // 列表最后一位
    private int mPage = 1;
    private int mSize = 10;
    private boolean hasMore = true;
    private List<HomeTagTwoItem> mTagList = new ArrayList<>();

    // 列表header
    private View mHeaderView;
    private BannerView mBannerView;
    private ModuleView mModuleView;

    private boolean isExpand = false;
    private boolean isScrollTop = false;

    @Override
    protected Context getFragmentContext() {
        return getActivity();
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initViews() {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) statusBar.getLayoutParams();
        params.height = Constant.HEIGHT_OF_STATUSBAR;
        params.width = Constant.WIDTH_OF_SCREEN;
        statusBar.setLayoutParams(params);

        mFooterView = new LoadMoreFooter(mContext);
        mHeaderView = LayoutInflater.from(mContext).inflate(R.layout.view_home_header, null);
        mBannerView = (BannerView) mHeaderView.findViewById(R.id.home_banner_view);
        mModuleView = (ModuleView) mHeaderView.findViewById(R.id.home_module_view);

//        swipeRefreshLayout.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.colorAccent));
        swipeRefreshLayout.setProgressViewOffset(true, 0,  (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 70, getResources().getDisplayMetrics()));

        mHomeListAdapter = new HomeTagAdapter(mContext, mTagList);
        mHomeListAdapter.addFooterView(mFooterView);
        mHomeListAdapter.addHeaderView(mHeaderView);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        recyclerView.setLayoutManager(mLinearLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mHomeListAdapter);
        recyclerView.setHasFixedSize(true);
    }

    @Override
    protected void initListeners() {

        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                isExpand = (verticalOffset >= 0);
                isCanRefresh();
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //到达底部时,加载更多
                int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition() + 1;
                if (mLinearLayoutManager.getChildCount() > 0
                        && mLinearLayoutManager.getItemCount() >= mLinearLayoutManager.getChildCount()
                        && lastVisiblePosition >= mLinearLayoutManager.getItemCount()
                        && dy > 0) {
                    mPosition = lastVisiblePosition;

                    if (hasMore) {
                        mFooterView.setStatus(LoadMoreFooter.Status.LOADING);
                        loadMore();
                    }
                }

                // 防止滑到列表中间时，下拉引起下拉刷新
                int topRowVewrticalPosition =
                        (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                isScrollTop = (topRowVewrticalPosition >= 0);
                isCanRefresh();
            }

//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                switch (newState) {
//                    case SCROLL_STATE_IDLE: // The RecyclerView is not currently scrolling.
//                        //当屏幕停止滚动，加载图片
//                        try {
//                            if (getContext() != null) Glide.with(getContext()).resumeRequests();
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                        break;
//                    case SCROLL_STATE_DRAGGING: // The RecyclerView is currently being dragged by outside input such as user touch input.
//                        //当屏幕滚动且用户使用的触碰或手指还在屏幕上，停止加载图片
//                        try {
//                            if (getContext() != null) Glide.with(getContext()).pauseRequests();
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                        break;
//                    case SCROLL_STATE_SETTLING: // The RecyclerView is currently animating to a final position while not under outside control.
//                        //由于用户的操作，屏幕产生惯性滑动，停止加载图片
//                        try {
//                            if (getContext() != null) Glide.with(getContext()).pauseRequests();
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                        break;
//                }
//            }
        });

        searchBar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, SearchActivity.class));
            }
        });
    }

    @Override
    protected void initLogic() {
        // 进入界面就刷新
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refresh();
                swipeRefreshLayout.setRefreshing(true);
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            swipeRefreshLayout.setRefreshing(false);
        }

        isCanRefresh();
    }

    /**
     * 判断是否可以下拉刷新
     */
    private void isCanRefresh() {
        if (isExpand && isScrollTop) {
            swipeRefreshLayout.setEnabled(true);
        } else {
            if (!swipeRefreshLayout.isRefreshing()) {
                swipeRefreshLayout.setEnabled(false);
            }
        }
    }

    /**
     * 下拉刷新
     */
    private void refresh() {
        mPage = 1;
        hasMore = true;
        loadModuleData();
        loadBannerData();
        loadListData();
    }

    /**
     * 上拉加载
     */
    private void loadMore() {
        mPage++;
        NetworkRequest.getInstance().getHomeTagList(mPage, mSize,
                new TupaiSubscriber<List<TagItem>>(mContext) {
                    @Override
                    protected void requestSuccess(List<TagItem> tagItems) {
                        if (tagItems.size() != 0) {
                            setListData(tagItems, 1);
                            mFooterView.setStatus(LoadMoreFooter.Status.GONE);
                        }
                        swipeRefreshLayout.setRefreshing(false);

                        if (tagItems.size() < mSize) {
                            mFooterView.setStatus(LoadMoreFooter.Status.THE_END);
                            hasMore = false;
                        }
                    }

                    @Override
                    protected void requestError(String error) {
                        mPage--;
                        mFooterView.setStatus(LoadMoreFooter.Status.GONE);
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }


    /**
     * 获取列表数据
     */
    private void loadListData() {
        mPage = 1;
        mFooterView.setStatus(LoadMoreFooter.Status.GONE);
        NetworkRequest.getInstance().getHomeTagList(mPage, mSize,
                new TupaiSubscriber<List<TagItem>>(mContext) {
                    @Override
                    protected void requestSuccess(List<TagItem> tagItems) {
                        if (tagItems.size() != 0) {
                            mTagList.clear();
                            setListData(tagItems, 0);
                        }
                        swipeRefreshLayout.setRefreshing(false);

                        if (tagItems.size() < mSize) {
                            mFooterView.setStatus(LoadMoreFooter.Status.THE_END);
                            hasMore = false;
                        }
                    }

                    @Override
                    protected void requestError(String error) {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    /**
     * 从源数据生成两个一组的数据
     */
    private void setListData(List<TagItem> tagItems, int type) {
        for (int i = 0; i < tagItems.size(); i = i + 2) {
            if (i < tagItems.size()) {
                List<TagItem> tempList = new ArrayList<>();
                HomeTagTwoItem item = new HomeTagTwoItem();
                tempList.add(tagItems.get(i));
                if ((i + 1) < tagItems.size()) {
                    tempList.add(tagItems.get(i + 1));
                }
                item.setTagItemList(tempList);
                mTagList.add(item);
            }
        }
        if (type == 0) {
            mHomeListAdapter.notifyDataSetChanged();
        } else {
            mHomeListAdapter.notifyItemInserted(mPosition);
        }
    }


    //-------------------------------- Header视图相关 ---------------------------------------------------------

    /**
     * 获取banner数据
     */
    private void loadBannerData() {
        final List<HomeBanner> list = new ArrayList<>();
        NetworkRequest.getInstance().getHomeBanner(new TupaiSubscriber<List<HomeBanner>>(mContext) {
            @Override
            protected void requestSuccess(List<HomeBanner> homeBanners) {
                if (homeBanners != null && homeBanners.size() != 0) {
                    list.addAll(homeBanners);
                    mBannerView.setBannerData(list);
                } else {
                    mBannerView.setVisibility(View.GONE);
                }
            }

            @Override
            protected void requestError(String error) {

            }
        });
    }

    /**
     * 获取module数据
     */
    private void loadModuleData() {
        List<View> list = new ArrayList<>();
        SingleModuleView askView = new SingleModuleView(mContext, SingleModuleView.TYPE_ASK);
        SingleModuleView hotView = new SingleModuleView(mContext, SingleModuleView.TYPE_HOT);
        SingleModuleView replyView = new SingleModuleView(mContext, SingleModuleView.TYPE_REPLY);

        list.add(askView);
        list.add(hotView);
        list.add(replyView);

        mModuleView.setModuleData(list);
        // 成功后开始加载视图
        mHomeListAdapter.addHeaderView(mHeaderView);
    }

}
